package com.gec.it.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.nio.charset.StandardCharsets;

public class SmsUtil {
    private String uid;
    private String key;

    public void setKey(String key) {
        this.key = key;
    }
    public void setUid(String uid) {
        this.uid = uid;
    }
    public String sendSms(String to,String content){
        return sendSms(this.uid,this.key,to,content);
    }
    public static String sendSms(String uid, String key, String to, String content)
    {
        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod("http://utf8.api.smschinese.cn");
            post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");//在头文件中设置转码
            NameValuePair[] data = {new NameValuePair("Uid", uid)
                    , new NameValuePair("Key", key)
                    , new NameValuePair("smsMob", to)
                    , new NameValuePair("smsText", content)};
            post.setRequestBody(data);//把参数提交给post请求
            client.executeMethod(post);
            String result = new String(post.getResponseBodyAsString().getBytes(StandardCharsets.UTF_8));
            System.out.println(result); //打印返回消息状态
            post.releaseConnection();
            return result;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
